<!--
 * @Author: zlw
 * @Date: 2023-08-25 16:29:14
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-08-25 16:30:57
 * @Description: 新同步培优占位
-->
<template>
  <div class="newSynchronization">
    <div class="newSynchronizationlist">
      <div class="newSynchLeft">
        <img :src="postersUrl" alt="" />
      </div>
      <div class="newSynchRight">
        <div class="newSynchRightTop">
          <p>{{ showCourseObj.parentName }}</p>
          <span>{{ showCourseObj.name }}</span>
        </div>
        <div class="newSynchRightBottom">
          <span>{{ syViewCount }}人已学</span>
          <img @click="togoTong" src="../../assets/images/lession/studyicon.png" alt="" />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { excellentServices, catalogServices } from '@/api';
import { getBookImage } from '../../api/getSynchronizationApi';
import { getJsonlocalStore } from '../../common/comfun';
import local from '@/utils/local.js';
import { findTreeLeaf, findTreeNodeById } from '@/utils/tree';
import { setRecordCountStat } from '@/utils/common.js';
import YouXin from 'youxin-js-sdk';
export default {
  name: 'NewSynchronization',
  props: {
    datas: Object
  },
  data () {
    return {
      versionArr: [],
      versionImage: [],
      postersUrl: '',
      // 当前用户相关信息
      currentInfo: {
        currentStageCode: '', // 当前学段编码
        currentGradeCode: '', // 当前年级编码
        currentTermCode: '', // 当前学期编码
        currentSubjectCode: '' // 当前学科编码
      },
      coursestyleCode: '', // coursestyleCode: '', // 当前科目对应的环节模板样式
      couseData: [],
      showCourseObj: {
        parentName: '',
        name: ''
      },
      activeBook: '',
      syViewCount: 0
    };
  },
  computed: {
    version: function () {
      let version = '';
      this.syncCatalogList.some(item => {
        if (item.id === this.bookId) {
          const infoObj = {};
          item.tags.some(tagItem => {
            infoObj[tagItem.tagId] = tagItem.enumName;
            infoObj[tagItem.tagId + 'Code'] = tagItem.enumCode;
          });
          this.coursestyleCode = infoObj.coursestyleCode ? infoObj.coursestyleCode : '';
          version = `${infoObj.edition ? infoObj.edition : ''}${infoObj.grade ? infoObj.grade : ''}${infoObj.volume ? infoObj.volume : ''}${infoObj.electivetype ? infoObj.electivetype : ''}`;
        }
      });
      return version;
    }
  },
  async created () {
     const userInitInfo = getJsonlocalStore('userInitInfo');
     if (userInitInfo) {
       this.currentInfo = {
        currentStageCode: userInitInfo.studentStageCode, // 当前学段编码
        currentGradeCode: userInitInfo.gradeCode, // 当前年级编码
        currentTermCode: userInitInfo.currentTermCode, // 当前学期编码
        currentSubjectCode: localStorage.getItem('currentSubjectCode') // 当前学科编码
       };
     }
     await this.getVersion();
     await this.getCourseData();
  },
  mounted () {
    setRecordCountStat(this.bookId).then(data => {
      this.recordList = JSON.parse(JSON.stringify(data));
      this.recordList.map(item => {
        if (this.bookId === item.resId) {
          this.syViewCount = item.viewCount;
        } else {
          const oldtimestamp = new Date('2023-02-22').getTime(),
            newtimestamp = Date.now(),
            timeSpan = Math.floor((newtimestamp - oldtimestamp) / (24.0 * 3600.0)), // 时间戳计算
            viewCount = 30 + (Math.floor(Math.random() * 20) + 1), // 生成随机数
            num = 299 * (viewCount + 1) + Math.floor(99 * Math.log(1 + 24 * timeSpan));// 计算公式
          this.syViewCount = num;
        }
      });
    });
  },
  methods: {
    // 获取课程
    async getCourseData (getBookIdFlag) {
      // 获取当前选择的版本
      if (!getBookIdFlag) {
        const param = {
          studyStageCode: this.currentInfo.currentStageCode,
          gradeCode: this.currentInfo.currentGradeCode,
          subjectCode: this.currentInfo.currentSubjectCode
        };
        if (this.currentInfo.currentStageCode !== '0003') {
          param.termCode = this.currentInfo.currentTermCode;
        }
        const bookRecord = await excellentServices.studentGetBookId(param);
        try {
          this.bookId = bookRecord.data.bookId;
        } catch (error) {
        }
      }
      const that = this,
        tagstr = that.currentInfo.currentStageCode === '0003' ? `section-0003,subject-${that.currentInfo.currentSubjectCode}` : `section-${that.currentInfo.currentStageCode},grade-${that.currentInfo.currentGradeCode},volume-${that.currentInfo.currentTermCode},subject-${that.currentInfo.currentSubjectCode}`,
        params = { tags: tagstr, pageNum: 1, pageSize: 100, status: 1 },
        res = await excellentServices.getCrouseList(params); // /catalogue/list_course
        that.syncCatalogList = res.data.syncList || [];
        this.getCourseReady = true;
        console.log(that.syncCatalogList, 'that.syncCatalogList---');
      // 如果有同步课程
      if (that.syncCatalogList.length > 0) {
        // 获取所有的版本信息 用于切换信息
        const versionArr = that.stuHomeEdiFormat(that.syncCatalogList, []), versionObj = {};
          // 12.23 libaochuan
        // 根据获取的 进度里面的bookId 定位当前版本
          // 根据获取的 进度里面的bookId 定位当前版本
        let parentId = '',
          childId = '',
          prevBookObj = versionArr.find(item => {
            // 根第一层id 匹配到 说明只有一层版本
            if (item.itemCode === this.bookId) {
              parentId = item.itemCode;
              childId = this.bookId;
              return true;
            }
            // 如果存在二级版本的时候，则说明根据 获取用户保存的版本 与 第二层版本匹配，
            if (item.childList) {
              let flag = false;
              item.childList.some(innerItem => {
                if (innerItem.itemCode === this.bookId) {
                  parentId = item.itemCode;
                  childId = this.bookId;
                  flag = true;
                  return true;
                }
              });
              return flag;
            }
          });
        if (!prevBookObj) {
          prevBookObj = versionArr[0];
          versionObj.versionArr = versionArr;
          versionObj.activeVersion = prevBookObj.itemCode;
          versionObj.semester = prevBookObj.childList ? prevBookObj.childList[0].itemCode : '';
          if (versionObj.semester) {
            this.bookId = versionObj.semester;
          } else {
            this.bookId = versionObj.activeVersion;
          }
          local.set('version', JSON.stringify(versionObj));
        } else {
          versionObj.versionArr = versionArr;
          versionObj.activeVersion = parentId;
          versionObj.semester = prevBookObj.childList ? childId : '';
          local.set('version', JSON.stringify(versionObj));
        }
        // 获取当前课程的对应的环节展示模板方式、
        if (!that.refreshFlag) { // 第一次请求的时候
          let syncObj = that.syncCatalogList.find(item => {
            return item.id === this.bookId;
          });
          if (!syncObj) {
            syncObj = that.syncCatalogList[0];
          }
          // 获取info 设置bookId 版本信息。二楼资源制作需要使用
          // const info = JSON.parse(local.get('info'));
          // info.version = syncObj.id;
          // local.set('info', JSON.stringify(info));
          that.refreshFlag = false;
          that.crouseType = syncObj.type;
          that.courseIsNew = syncObj.isNew;
        }
        // 根据当前第一个课程的类型获取目录
        if (that.crouseType === 4) {
          // 获取同步培优模块
          this.getSyncCrouseTreeData(that.bookId, that.courseIsNew);
        }
      }
    },
    stuHomeEdiFormat (course = [], arr = []) {
      const taget = [];
      course.forEach(item => {
        item.tags && item.tags.forEach(v => {
          if (v.tagId === 'edition') {
            const obj = Object.assign({}, v, { tags: item.tags });
            obj.fileUrl = item.fileUrl;
            obj.boId = item.id;
            taget.push(obj);
          }
        });
      });
      const arys = [];
      taget.forEach(item => {
        if (!arys.includes(item.enumCode)) {
          arr.push(item);
        } else {
          const num = arr.findIndex(h => h.enumCode === item.enumCode);
          arr[num].tags = arr[num].tags.concat(item.tags);
        }
        arys.push(item.enumCode);
      });
      arr.forEach(item => {
        item.tags.forEach(v => {
          if (v.tagId === 'electivetype') {
            if (item.childList) {
              item.childList.push(v);
            } else {
              item.childList = [v];
            }
          }
        });
      });
      return arr;
    },
    // 获取同步培优课程目录  根据bookId
    async getSyncCrouseTreeData (bookId, isNew) {
      const that = this,
        params = { bookId: bookId, isNew: isNew },
        res = await excellentServices.getSyncCrouseTree(params); // catalogue/list_sync_course
      that.catalogTree = res.data.childList || [];
      that.treeData = res.data;
      if (that.catalogTree.length === 0) {
        this.syncModleList = []; // 同步模块职位空数组
      }
      // // 获取目录书中所有叶子节点集合
      console.log(that.catalogTree, 'siou');
      const cataArr = findTreeLeaf(that.catalogTree, []);
      that.couseData = cataArr;
      const couseDataLength = that.couseData.filter(item => item.id === that.currentId);
      console.log(couseDataLength, 'couseDataLength', that.couseData[0]);
      that.showCourseObj = couseDataLength.length > 0 ? couseDataLength[0] : that.couseData[0];
      that.showCrouseIndex = this.couseData.findIndex(v => v.id === this.currentId) > 0 ? this.couseData.findIndex(v => v.id === this.currentId) : 0;
      // 获取用户目录当前进度
      that.getUserCatalogId(bookId).then(res => {
        // 最新进度无数据或在目录树上找不到，默认展示目录树上第一个叶子节点
        if (!res || findTreeNodeById(that.catalogTree, [], res).length < 1) {
          if (cataArr[0]) {
            that.currentId = cataArr[0].id;
            that.catalogId = cataArr[0].id;
          } else {
            that.moduleInfo = {};
          }
        } else {
          const redObj = findTreeNodeById(that.catalogTree, [], res)[0];
          that.currentId = redObj.id;
          that.catalogId = redObj.id;
        }
      });
    },
    // 获取书本的版本
    async getVersion () {
      const version = JSON.parse(local.get('version'));
      if (version) {
        this.versionArr = version.versionArr || [];
        this.activeBook = version.activeVersion;
        const newArr = [];
        this.versionArr.forEach(item => {
          newArr.push(item.boId);
        });
        const verImgRes = await getBookImage({ codes: newArr.join(',') });
        if (verImgRes.code === '200') {
          this.versionImage = verImgRes.data;
        }
        newArr.map(item => {
          this.versionImage.map(ite => {
            if (item === ite.id) {
              this.postersUrl = ite.url;
            }
          });
        });
      }
    },
    // 获取用户最新进度
    async getUserCatalogId (bookId) {
      const res = await catalogServices.getUsedCatalog(bookId); // /user/book/progress/
      return res.data.catalogId;
    },
    togoTong () {
      YouXin.openWindow({
        url: `${window.hostOrigin}/nrmsui/resourceapl/student/asyPriTutor?bookId=` + this.bookId + '&subjectCode=' + this.datas.setStyle.subjectCode, // 网页地址
        title: this.showCourseObj.parentName || this.showCourseObj.name,
        showHeader: '0'
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.newSynchronization {
  padding: 0 16px;
  margin: 16px auto;
  .newSynchronizationlist {
    // width: 343px;
    height: 140px;
    background: #ffffff;
    box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    padding: 12px;
    display: flex;
    // align-items: center;
    .newSynchLeft {
      width: 105px;
      margin-right: 20px;
      img {
        width: 100%;
        border-radius: 6px;
      }
    }
    .newSynchRight {
      margin-top: 10px;
      width: 200px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .newSynchRightTop {
        p {
          font-size: 16px;
          font-family: PingFang SC-Heavy, PingFang SC, sans-serif;
          font-weight: 800;
          color: #333333;
          line-height: 19px;
        }
        span {
          font-size: 14px;
          font-family: PingFang SC-Regular, PingFang SC, sans-serif;
          font-weight: 400;
          color: #666666;
          line-height: 16px;
        }
      }
      .newSynchRightBottom {
        display: flex;
        align-items: center;
        justify-content: space-between;
        span {
          font-size: 12px;
          font-family: PingFang SC-Regular, PingFang SC, sans-serif;
          font-weight: 400;
          color: #666666;
          line-height: 14px;
          display: block;
        }
        img {
          width: 60px;
          height: 25px;
          display: block;
        }
      }
    }
  }
}
</style>
